package com.wingsfrog.puzzle.service.impl;

import com.wingsfrog.puzzle.controller.dto.response.PlayListDto;
import com.wingsfrog.puzzle.controller.dto.response.RecordDto;
import com.wingsfrog.puzzle.controller.dto.response.UserResDto;
import com.wingsfrog.puzzle.modules.dao.PuzzleRecordDao;
import com.wingsfrog.puzzle.modules.entity.Picture;
import com.wingsfrog.puzzle.modules.entity.PuzzleRecord;
import com.wingsfrog.puzzle.service.PuzzleRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class PuzzleRecordServiceImpl implements PuzzleRecordService{
    @Autowired
    PuzzleRecordDao dao;

    @Override
    public PuzzleRecord get(Integer recordId) {
        return dao.findOne(recordId);
    }

    @Override
    public List<RecordDto> getScoreBoard(Integer picId) {
        return dao.findScoreBoard(picId);
    }

    @Override
    public void update(Integer userId, Integer picId, Integer step, Integer time) {
        PuzzleRecord record = dao.getRecord(userId, picId);
        if (record == null) {
            record = new PuzzleRecord();
            record.setUserId(userId);
            record.setPictureId(picId);
            record.setStep(step);
            record.setTime(time);
            record.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        } else if (record.getStep().compareTo(step) > 0 &&
                record.getTime().compareTo(time) > 0) {
            record.setStep(step);
            record.setTime(time);
            record.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        }
        dao.save(record);
    }

    @Override
    public List<PlayListDto> getPlayList(Integer userId) {
        List<Picture> playList = dao.getPlayList(userId);
        List<PlayListDto> playListDtos = new ArrayList<>();
        playList.forEach(picture -> {
            PlayListDto dto = new PlayListDto();
            dto.setPath(picture.getPath());
            dto.setPicId(picture.getId());
            playListDtos.add(dto);
        });
        return playListDtos;
    }

    @Override
    public List<PlayListDto> getOccupyList(Integer userId) {
        Object[] objs =  dao.getOccupyList(userId);
        List<PlayListDto> dtoList = new ArrayList<>();
        for (Object obj : objs) {
            PlayListDto dto = new PlayListDto();
            Object[] innerObj = (Object[]) obj;
            dto.setPicId((Integer)innerObj[0]);
            dto.setPath((String)innerObj[1]);
            dto.setHardness((Integer)innerObj[2]);
            dtoList.add(dto);
        }
        return dtoList;
    }

    @Override
    public List<UserResDto> getUserList(Integer picId) {
        List<UserResDto> users = dao.getUserList(picId);
        return users;
    }

}
